from django.test import TestCase
from django.utils import translation

from index.models import Movie
from index.serializers import MovieSerializer

class SerializersTestCase(TestCase):
    def setUp(self):
        self.data = {
            'name': {
                'en': 'Shrek',
                'ru': 'Шрек'
            }
        }

    def test_serializer_updates_single_language(self):
        serializer = MovieSerializer(data=self.data)

        serializer.is_valid(raise_exception=True)

        serializer.save()

        instance = serializer.instance

        data = {
            'name': {
                'ru': 'Шрек 2'
            }
        }

        serializer = MovieSerializer(instance, data=data, partial=True)

        serializer.is_valid(raise_exception=True)

        serializer.save()

        data = serializer.data

        self.assertEquals(data['name']['en'], self.data['name']['en'])

        self.assertEquals(data['name']['ru'], 'Шрек 2')


    def test_serializer_saves_creates_instance(self):
        serializer = MovieSerializer(data=self.data)

        serializer.is_valid(raise_exception=True)

        serializer.save()

        instance = serializer.instance

        name = self.data['name']

        for language in name:
            translation.activate(language)

            self.assertEquals(name[language], instance.name)

    def test_serializer_creates_instance_with_partial_language_set(self):
        data = self.data.copy()

        del data['name']['ru']

        serializer = MovieSerializer(data=self.data)

        serializer.is_valid(raise_exception=True)

        serializer.save()

        instance = serializer.instance

        name = serializer.data['name']
        
        for language in name:
            self.assertEquals(name[language], data['name'].get(language, ''))

